//
//  YDSettingViewController.m
//  PeiZiWangBei
//
//  Created by 巨彦新 on 2018/1/2.
//  Copyright © 2018年 LK-IOS. All rights reserved.
//

#import "YDSettingViewController.h"
#import "YDAccountSettingCell.h"
#import "YDAboutUsViewController.h"
#import <AFNetworking.h>
#import <SDWebImage/SDImageCache.h>

@interface YDSettingViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UITableView *tableView;

@end

@implementation YDSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置";
    self.view.backgroundColor = [UIColor colorWithHexString:mainGray];
    [self tableView];
}


#pragma UITableViewDelegate , UITableViewDataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDAccountSettingCell *cell = [YDAccountSettingCell cellWithTableView:tableView];
    cell.accImage.hidden = YES;
    cell.setStatus.hidden = YES;
    cell.phoneLabel.hidden = YES;
    
    if ([SYUserInformation sharedInstance].isLogin) {
        if (indexPath.section == 0) {
            if (indexPath.item == 0) {
                cell.imageName = @"wd-shezhi-qingxhuhuancun";
                cell.cateString = @"清除缓存";
                cell.phoneLabel.hidden = NO;
                NSInteger byteSize = [[SDImageCache sharedImageCache] getSize];
                
                if (byteSize/1024 > 1024) {
                    float MbSize = byteSize/1024/1024;
                    cell.phoneLabel.text = [NSString stringWithFormat:@"%.1fM",MbSize];
                }else
                {
                    float MbSize = byteSize/1024;
                    cell.phoneLabel.text = [NSString stringWithFormat:@"%.1fK",MbSize];
                }
                cell.phoneLabel.textColor = NumberColor(129, 128, 129);
                
            }else{
                cell.imageName = @"wd-shezhi-guanyuwomen";
                cell.cateString = @"关于我们";
                cell.accImage.hidden = NO;
            }
        }else{
            cell.imageName = @"wd-zhsz-tuichudenglu";
            cell.cateString = @"退出登录";
        }
    }else{
        if (indexPath.item == 0) {
            cell.imageName = @"wd-shezhi-qingxhuhuancun";
            cell.cateString = @"清除缓存";
            cell.phoneLabel.hidden = NO;
            cell.phoneLabel.textColor = NumberColor(129, 128, 129);
            cell.phoneLabel.text = [self getCacheSize];
        }else{
            cell.imageName = @"wd-shezhi-guanyuwomen";
            cell.cateString = @"关于我们";
            cell.accImage.hidden = NO;
        }
    }
    
    return cell;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([SYUserInformation sharedInstance].isLogin) {
        return 2;
    }else{
        return 1;
    }
}
//
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([SYUserInformation sharedInstance].isLogin) {
        if (section == 0) {
            return 2;
        }else{
            return 1;
        }
    }else{
        return 2;
    }
    
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = NumberColor(247, 247, 247);
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return isPhoneX ? rateX812(10) : rate750(10);
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([SYUserInformation sharedInstance].isLogin) {
        if (indexPath.section == 0) {
            
            if (indexPath.item == 0) {
                [self clearCache];//清除缓存
            }else{//关于我们
                YDAboutUsViewController *vc = [[YDAboutUsViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }else{
            [self postExistView];
        }
        
    }else{
        if (indexPath.item == 0) {//清除缓存
            [self clearCache];
        }else{//关于我们
            YDAboutUsViewController *vc = [[YDAboutUsViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return isPhoneX ? rateX812(50) : rate750(50);;
}

//退出登录提示框
-(void)postExistView
{
    LK(weakSelf)
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"确认退出登录?" ButtonTitle:@"确定" ButtonClickBlock:^{
        
        
        [weakSelf logoutRequest];
        
        [weakSelf.pz_popupController dismiss];
    }];
    weakSelf.pz_popupController = [[PZPopUpController alloc] init];
    [weakSelf.pz_popupController dropAnimatedWithRotateAngle:30];
    [weakSelf.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
    
}
//清除缓存
-(void)clearCache
{
    LK(weakSelf)
    PZTipsAlertView *alert = [PZTipsViewManger shareDoubleTipsAlertViewTitle:@"提示" Mesage:@"确认清除缓存？" CancleTitle:@"取消" SureTitle:@"确定" CancleBlock:^{
        [weakSelf.pz_popupController dismiss];
        
    } SureBlock:^{
        
        [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
            [weakSelf.tableView reloadData];
        }];
        [weakSelf.pz_popupController dismiss];
        
    }];
    weakSelf.pz_popupController = [[PZPopUpController alloc] init];
    [weakSelf.pz_popupController dropAnimatedWithRotateAngle:30];
    [weakSelf.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}
//获取缓存
-(NSString *)getCacheSize
{
    NSInteger byteSize = [[SDImageCache sharedImageCache] getSize];
    
    if (byteSize/1024 > 1024) {
        float MbSize = byteSize/1024/1024;
        return [NSString stringWithFormat:@"%.1fM",MbSize];
    }else
    {
        float MbSize = byteSize/1024;
        return [NSString stringWithFormat:@"%.1fK",MbSize];
    }
}


-(void)logoutRequest
{
    
    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFJSONRequestSerializer serializer];//声明请求的参数类型为json类型
    
    [manager.requestSerializer setValue:[[SYUserDataManger sharedInstance] getUserToken] forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"I" forHTTPHeaderField:@"endType"];
    
    //网络请求超时的时间
    manager.requestSerializer.timeoutInterval = 30;
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects: @"text/html",@"text/json", @"application/json", @"text/javascript" ,@"text/plain",nil];
    ((AFJSONResponseSerializer *)manager.responseSerializer).removesKeysWithNullValues = YES;
    
    
    NSString *url = [baseUrlHttp stringByAppendingString:@"/logout"];
    
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"退出登录失败" isExistNav:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        if (error.code == NSURLErrorBadServerResponse && [error.userInfo[@"NSLocalizedDescription"] isEqualToString:@"Request failed: forbidden (403)"]) {
            //影藏小红点
            [[NSNotificationCenter defaultCenter] postNotificationName:kShowRedPointNoti object:@(NO)];
            
            //注销成功
            [[SYUserDataManger sharedInstance] deleteUserDataTable];
            
            [SYUserInformation sharedInstance].isLogin = NO;
            
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"退出登录失败" isExistNav:YES];
        }
        
    }];
    
    
}
/*******tableView********/
-(UITableView *)tableView
{
    if (_tableView == nil) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, self.view.height - self.tabBarController.tabBar.height) style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        tableView.backgroundColor = NumberColor(247, 247, 247);
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.scrollEnabled = NO;
        tableView.tableFooterView = [UIView new];
        if (isIos11) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView = tableView;
    }
    return _tableView;
}

@end
